<template>
  <div>
    <div class="m-searchPanel">
      <div class="layout-1"><span class="leftLine"></span>查询条件</div>
      <div class="layout-2">
        <el-form :model="searchForm" :inline="true">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item class="input-with-select">
                <el-input placeholder=" " v-model.trim="searchForm.inputFH" clearable>
                  <el-select v-model="searchForm.typeinputFH" slot="prepend" placeholder="请选择"
                             class="selectInputType">
                    <el-option label="主题" value="theme"></el-option>
                    <el-option label="单号" value="fid"></el-option>
                    <el-option label="名单" value="typeId"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="" class="select-timepick">
                <el-select placeholder="请选择" v-model="searchForm.typetimeFH">
                  <el-option label="创建时间" value="create"></el-option>
                  <el-option label="分配时间" value="assign"></el-option>
                  <el-option label="预约时间" value="resv"></el-option>
                </el-select>
                <el-date-picker
                  v-model="searchForm.timeFH"
                  type="datetimerange"
                  :editable="false"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00','23:59:59']"
                  format="yyyy-MM-dd HH:mm:ss"
                  :unlink-panels="true"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="7" class="searchBtns">
              <el-button type="text" @click="showMoreSearchChoise =!showMoreSearchChoise"><span>更多条件</span><i :class="{
              'el-icon-arrow-down':!showMoreSearchChoise,
              'el-icon-arrow-up':showMoreSearchChoise,
              }"></i>
              </el-button>
              <el-button type="primary" icon="el-icon-search" @click="search" :loading="dataListLoading">查询</el-button>
              <el-button type="primary" plain icon="el-icon-refresh" @click="reset">重置</el-button>
            </el-col>
          </el-row>
          <el-collapse-transition>
            <el-row :gutter="30" v-if="showMoreSearchChoise">
              <el-col :span="6">
                <el-form-item label="名单类型">
                  <el-select v-model="searchForm.type" placeholder="请选择" clearable>
                    <el-option label="真实账号" value="1"></el-option>
                    <el-option label="LEAD" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分配状态">
                  <el-select v-model="searchForm.astatus" placeholder="请选择" clearable>
                    <el-option label="待分配" value="1"></el-option>
                    <el-option label="已分配" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标记">
                  <el-select
                    v-model="searchForm.labels"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteMarkMethod"
                    placeholder="请输入关键词"
                  >
                    <el-option
                      v-for="item in markabels"
                      :label="item.lname"
                      :key="item.lid"
                      :value="item.lid">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-transition>
        </el-form>
      </div>
    </div>
    <div class="m-dataLayout">
      <div class="m-searchListPanel">
        <div class="layout-1"><span class="leftLine"></span>信息列表</div>
        <el-row class="layout-2">
          <el-col :span="3">
            <el-button type="text" icon="el-icon-plus" @click="showAddFollowUpData=true"
                       v-if="buttonAuthority.ifollow && buttonAuthority.ifollow.create">新建
            </el-button>
          </el-col>
          <el-col :span="21">
            <el-tabs v-model="activeTab" class="m-common-tab index-common-tab" type="card" @tab-click="handleClickTab">
              <el-tab-pane name="1"><span slot="label">待处理（{{countInfo.todo}}）</span></el-tab-pane>
              <el-tab-pane name="2"><span slot="label">处理中（{{countInfo.doing}}）</span></el-tab-pane>
              <el-tab-pane name="3"><span slot="label">已完成（{{countInfo.finish}}）</span></el-tab-pane>
              <el-tab-pane name="4"><span slot="label">已取消（{{countInfo.cancel}}）</span></el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>
      <div class="m-dataList">
        <el-table
          :data="dataList"
          ref="dataList"
          style="width: 100%"
          v-loading="dataListLoading"
          element-loading-text="loading..."
          max-height="700"
          @sort-change="tableSortBy"
        >
          <el-table-column
            prop="id"
            width="160"
            label="单号">
            <template slot-scope="scope">
              <a href="javascript:void(0)" @click="fnShwoDetails(scope.row)">{{scope.row.id}}</a>
            </template>
          </el-table-column>
          <el-table-column
            prop="theme"
            label="主题"
            show-overflow-tooltip
            width="120">
          </el-table-column>
          <el-table-column
            prop="type"
            label="名单类型"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.type | typeToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeId"
            label="名单"
            width="120">
            <template slot-scope="scope">
              <a href="javascript:void(0)" @click="toInfo(scope.row)">{{scope.row.typeId}}</a>
            </template>
          </el-table-column>
          <el-table-column
            prop="resvTimeStr"
            label="预约时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="resvSndTimeStr"
            label="预约提醒"
            width="160">
          </el-table-column>
          <el-table-column
            prop="hstatus"
            label="处理状态"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.hstatus | hstatusFollowUpToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="astatus"
            label="分配状态"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.astatus | astatusToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="assigner"
            label="分配给"
            width="100">
          </el-table-column>
          <el-table-column
            prop="assignTimeStr"
            label="分配时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人"
            width="120">
          </el-table-column>
          <el-table-column
            prop="createTimeStr"
            label="创建时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="labels"
            label="标记"
            width="200">
            <template slot-scope="scope">
              <Comp-tags :label="scope.row.labels"></Comp-tags>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            v-if="buttonAuthority.ifollow && (buttonAuthority.ifollow.edit || buttonAuthority.ifollow.label)"
            align="center"
            fixed="right"
            width="100">
            <template slot-scope="scope">
              <el-dropdown
                :show-timeout="200"
                trigger="click"
                @command="(type)=>{rolDataActive(type,scope.row)}"
              >
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  size="small">
                  更多操作
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit" v-if="buttonAuthority.ifollow && buttonAuthority.ifollow.edit">编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="mark" v-if="buttonAuthority.ifollow && buttonAuthority.ifollow.label">标记
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="m-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes=pagination.pageSizeList
          :current-page=pagination.pageNo
          :page-size=pagination.pageSize
          layout="total, sizes, prev, pager, next"
          :total=pagination.total>
        </el-pagination>
      </div>
    </div>
    <Comp-Add-Follow-Up @addSuccess="addSuccess" :show.sync="showAddFollowUpData" from="desktop"></Comp-Add-Follow-Up>
    <Comp-Mark @submit="markRowData" :show.sync="showMarkDialog"
               :markData="{type:'3',labelsStr:activeRow.labels}"></Comp-Mark>
    <Comp-Follow-Up-Details @submit="upLoadSubmit" :rowDetails="activeRow" :show.sync="showDetails"
                            from="desktop"></Comp-Follow-Up-Details>
  </div>
</template>

<script>
  import {mapGetters} from "vuex";
  import * as FollowUpAPI from '@/Api/followup';
  import * as LabelAPI from '@/Api/label'
  import * as Utils from '@/utils'
  import CompAddFollowUp from '@/components/CompAddFollowUp.vue'
  import CompFollowUpDetails from '@/components/CompFollowUpDetails.vue'
  export default {
    name: 'TheMyFollowUp',
    data () {
      return {
        activeTab: '',
        showAddFollowUpData: false,
        searchForm: {
          typeinputFH: 'typeId',
          inputFH: '',
          typetimeFH: 'assign',
          timeFH: Utils.thisWeek(),
          type: '',
          labels: [],
//          hstatus: [],
          astatus: '',
          createUser: '',
          assigner: '',
        },
        markabels: [],
        copySearchForm: null,
        activeRow: {},//当前操作数据
        countInfo: {},
        showMarkDialog: false,
        showMoreSearchChoise: false,
        showDetails: false,
        pagination: Utils.commonPagination(),
        pickerOptions: Utils.pickerOptions(),
        dataList: [],
        dataListLoading: false,
        sortInfo: {},
        ajaxSearchParams: {},
      }
    },
    props: ['nowTab'],
    computed: {
      ...mapGetters(["buttonAuthority"]),
    },
    components: {
      CompAddFollowUp,
      CompFollowUpDetails
    },
    watch: {
      'searchForm.inputFH'(val){
        if (val) {
          this.searchForm.timeFH = null;
        } else {
          this.searchForm.timeFH = Utils.thisWeek();
        }
      },
      'nowTab'(val, oldval){
        if (val == 'followup') {
          this.dataList = JSON.parse(JSON.stringify(this.copyDataList))
        }
        if (oldval == 'followup') {
          this.dataList = [];
        }
        this.$refs.dataList.doLayout();
      }
    },
    methods: {
      handleClickTab() {
        if (this.activeTab) {
          this.searchForm.hstatus = [this.activeTab];
          if (this.pagination.pageNo == 1) {
            this.queryList();
          } else {
            this.pagination.pageNo = 1;
          }
        }
      },
      remoteMarkMethod(queryStr) {
        if (queryStr != '') {
          LabelAPI.labelName({
            type: '3',
            input: queryStr
          })
            .then(res => {
              if (res.code != 0) {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warning'
                })
                return;
              }
              this.markabels = res.data;
            })
            .catch(error => {
              console.log(error);
            })
        }
      },
      doLayoutTable(){
        if (this.$refs.dataList) {
          this.$refs.dataList.doLayout();
        }
      },
      markRowData(data){
        FollowUpAPI.ifollowLabel(Object.assign({
          id: this.activeRow.id,
          type: this.activeRow.type,
          typeId: this.activeRow.typeId
        }, data.mark))
          .then(res => {
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.queryList();
            this.showMarkDialog = false;
            this.$message({
              message: '标记成功',
              type: 'success'
            });
          })
          .catch(error => {
            console.log(error)
          })

      },
      rolDataActive(type, row) {
        if (type == 'edit') {
          /*这里有坑，请合并对象之后再赋值*/
          this.activeRow = Object.assign({editType: 'edit'}, row)
          this.showDetails = true;
        } else if (type == 'mark') {
          this.activeRow = row;
          this.showMarkDialog = true;
        }
      },
      fnShwoDetails(row) {
        this.activeRow = row;
        this.showDetails = true;
      },
      createListParams() {
        return Object.assign(this.ajaxSearchParams, {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        }, this.sortInfo)
      },
      tableSortBy(data) {
        if (!data.order) {
          return;
        }
        this.sortInfo.orderParam = data.prop;
        this.sortInfo.orderType = data.order.substr(0, data.order.length - 6);
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      queryList(){
        this.dataListLoading = true;
        if (this.$refs.dataList) {
          this.$refs.dataList.bodyWrapper.scrollTop = 0;
        }
        FollowUpAPI.followMyList(this.createListParams())
          .then(res => {
            this.dataListLoading = false;
            if (res.code != 0) {
              this.$notify({
                title: '温馨提示',
                message: res.msg,
                type: 'warning'
              })
              return;
            }
            this.dataList = res.data.data;
            this.pagination.total = res.data.total;
            this.copyDataList = JSON.parse(JSON.stringify(this.dataList));
          })
          .catch(error => {
            this.dataListLoading = false;
            console.log(error)
          })
      },
      upLoadSubmit(){
        this.queryList();
        this.queryCount();
      },
      queryCount(){
        FollowUpAPI.followIcount(this.createListParams())
          .then(res => {
            if (res.code != 0) {
              this.$notify({
                title: '温馨提示',
                message: res.msg,
                type: 'warning'
              })
              return;
            }

            this.countInfo = res.data;
          })
          .catch(error => {
            console.log(error)
          })
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size;
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleCurrentChange(index) {
        this.pagination.pageNo = index;
        this.queryList();

      },
      search() {
        this.ajaxSearchParams = Utils.searchParamsFormat(this.searchForm);
        if (this.pagination.pageNo == 1) {
          this.queryList();
          this.queryCount();
        } else {
          this.queryCount();
          this.pagination.pageNo = 1;
        }
      },
      addSuccess() {
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      reset() {
        this.searchForm = Object.assign({}, this.copySearchForm)
      },
      resetView(){
        this.showMoreSearchChoise = false;
        this.dataList = [];
        this.sortInfo = {};
        this.searchForm = Object.assign({}, this.copySearchForm);
        this.pagination = Utils.commonPagination();
        this.$refs.dataList.clearSort();
        this.search();
        this.queryCount();
      },
      toInfo(row) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
        });
        FollowUpAPI.followBelongInfo({
          type: row.type,
          typeId: row.typeId,
        })
          .then(res => {
            loading.close();
            if (res.code != '0') {
              this.$notify({
                title: '温馨提示',
                message: res.msg,
                type: 'warning'
              })
              return;
            }
            if (row.type == '1') {
              this.$router.push({
                name: 'AccountDetailsInfo',
                params: {
                  id: res.data.id + '_' + row.typeId + '_' + res.data.phone
                }
              })
            } else if (row.type == '2') {
              this.$router.push({
                name: 'LeadDetailsLeade',
                params: {
                  id: res.data.id + '_' + row.typeId
                }
              })
            }
          })
          .catch(error => {
            loading.close();
            console.log(error);
          })
      }
    },
    created(){
      this.copySearchForm = Object.assign({}, this.searchForm);
      this.search();
    }
  }
</script>

<style scoped lang="scss">

</style>
